package com.lucfzy.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.lucfzy.jwt.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    // 只有登录了之后，再次访问接口的时候才会去校验是否有权限。
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("token");
        // 如果token过期会抛出异常。
        try {
            JWTUtil.verifyToken(auth);
        } catch (TokenExpiredException e){
            throw new TokenExpiredException("token已过期或空，请重新登录");
        }
        return true;
    }

}
